package com.lsj.config.security.handler;

import cn.hutool.http.ContentType;
import com.alibaba.fastjson.JSONObject;
import com.lsj.core.exception.CustomerException;
import com.lsj.core.response.CommonResult;
import com.lsj.core.response.ResponseType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @Author:lin.sj
 * @Data:2021/7/7 0:04
 * @Desc: 权限不足处理器，返回权限不足提示
 */
@Component
public class MyAccessDeinedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException e) throws IOException, ServletException {
        response.setContentType(ContentType.build(ContentType.JSON.getValue(), Charset.forName("UTF-8")));
        response.getWriter().write(JSONObject.toJSONString(CommonResult.error(new CustomerException(ResponseType.forbid,"权限不足，不允许访问！"))));
    }
}
